package com.rankeiot.easy.vue;

import com.rankeiot.easy.vue.handler.LessHandler;
import com.rankeiot.easy.vue.handler.PathConvertHandler;
import com.rankeiot.easy.vue.handler.VueDevHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.resource.EncodedResourceResolver;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Configuration
@ConditionalOnWebApplication
public class EasyVueConfiguration implements WebMvcConfigurer, WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Value("${spring.profiles.active:default}")
    private String active;
    @Value("${server.dev:false}")
    private boolean dev;

    public static boolean devModel=false;
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 是否为开发模式
     *
     * @return
     */
    private boolean isDevModel() {

        return "dev".equals(active) || dev;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        devModel=isDevModel();
        ResourceHandlerRegistration publicRes = registry.addResourceHandler("/**");


        File fileDir = new File("public");
        // if(fileDir.exists()&&fileDir.isDirectory()){
        String path = "file:" + fileDir.getAbsolutePath() + "/";
        publicRes.addResourceLocations(path);
        // }

        ResourceHandlerRegistration vueRes = registry.addResourceHandler("/js/vue.js")
                .addResourceLocations("classpath:/vue/");
        if (isDevModel()) {
            String resPath = resourceLoader.getClassLoader().getResource("./").getPath();
            if (resPath.endsWith("target/classes/")) {
                resPath = resPath.replaceFirst("target/classes/", "");
                publicRes.addResourceLocations("file:" + resPath + "src/main/resources/static/");
            } else if (resPath.endsWith("target/test-classes/")) {
                resPath = resPath.replaceFirst("target/test-classes/", "");
                publicRes.addResourceLocations("file:" + resPath + "src/test/resources/static/", "file://" + resPath + "src/main/resources/static/");
            }
            publicRes.resourceChain(false).addResolver(new EncodedResourceResolver());
            vueRes.resourceChain(false).addResolver(new EncodedResourceResolver());

        } else {
            //正式服务器上，浏览器缓存5分钟
            publicRes.setCacheControl(CacheControl.maxAge(5, TimeUnit.MINUTES).cachePublic())
                    .resourceChain(true)
                    .addResolver(new EncodedResourceResolver());
            vueRes.setCacheControl(CacheControl.maxAge(5, TimeUnit.MINUTES).cachePublic())
                    .resourceChain(true).addResolver(new EncodedResourceResolver());
        }
        publicRes.addResourceLocations("classpath:/static/", "classpath:/META-INF/resources/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //registry.addInterceptor()
       // String s = getClass().getResource("/").toString();
        if (isDevModel()) {

            //处理mjs
           // registry.addInterceptor(new MJSHandler(resourceLoader)).addPathPatterns("/**/*.js");
            //处理less
            registry.addInterceptor(new LessHandler(resourceLoader)).addPathPatterns("/**/*.css");
            //vue 无需处理，直接返回
            registry.addInterceptor(new VueDevHandler(resourceLoader)).addPathPatterns("/**/*.vue");
        } else {
            //转换vue=>js
            registry.addInterceptor(new PathConvertHandler("application/json", "vue", "js")).addPathPatterns("/**/*.vue");
        }
    }

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        if (isDevModel()) {
            mappings.add("vue", "text/html");
        }
        factory.setMimeMappings(mappings);
    }
}
